<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 学生管理
 *
 * @icon fa fa-circle-o
 */
class Student extends Backend
{
    
    /**
     * Student模型对象
     * @var \app\admin\model\Student
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Student;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,
     * 除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','teamid'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['uid','number','name','team_id','card','in_date','birthday_date','dad_name','mom_name','dad_tel','mom_tel']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['avatar']);
				$row->visible(['teamid']);
				$row->getRelation('teamid')->visible(['name','teacher_id','grade']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }




    public function insert_student_params($data)
    {

        $v_arr = [
            $data['id'],//rowid
        $data['id'],//'admin',//
        'e10adc3949ba59abbe56e057f20ftest',
        $data['card'],//cardnum
        'hr',
        '1',
        'ALL',
        'all',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        '2018-01-01 00:00:00',
        '2028-01-01 23:59:59',
        'nan',
        0,
        'wu'];

        $f_arr = [ 'staffnum',
        'staffname',
        'signature',
        'cardnum',
        'departmentname',
        'departmentID',
        'controlerNum',
        'gatenum',
        'periodofvalitystart',
        'periodofvalityend',
        'jingruqishi1',
        'jingrujieshu1',
        'likaiqishi1',
        'likaijieshu1',
        'jingruqishi2',
        'jingrujieshu2',
        'likaiqishi2',
        'likaijieshu2',
        'jingruqishi3',
        'jingrujieshu3',
        'likaiqishi3',
        'likaijieshu3',
        'jingruqishi4',
        'jingrujieshu4',
        'likaiqishi4',
        'likaijieshu4',
        'staffgender',
        'staffage',
        'picfilename'];
        $in_data = array();
        foreach($f_arr as $key => $val){
            $in_data[$val] = $v_arr[$key]; 
        }
        //修改
        $card=$this->card_db();
        $where['cardnum'] = $data['card'];
        $where['staffname']  = $data['id'];
      
        // halt($in_data);
        $card_data = $card->name('staffbasesetting')->where($where)->find();
        if($card_data){
            $card->name('staffbasesetting')->where('staffname',$data['id'])->update($in_data);
        }else{
            $card->name('staffbasesetting')->insert($in_data);
        }
        
       $m["dwdevice"] =   "2021001";
       $m["trans_id"] =    "494fb911ee981b6595d8251064de432a";
       $m["cmd_code"] =    "DW_UPDATE_USERINFO";
       $m["idcard"] = strval($data['card']);
       $m["userid"] = strval($data['id']);
       $m["staffsign"] =  "";
       $m["departmentname"] = "9";
       $m["name"] =   $data['name'];
       $m["gatenumber"] = "all";
       $m["periodofvalitystart"] =     "2021-06-02 00:00:00";
       $m["periodofvalityend"] =   "2031-06-02 23:59:59";
       $m["jingruqishi1"] =    "2021-06-02 00:00:00";
       $m["jingrujieshu1"] =   "2031-06-02 23:59:59";
       $m["likaiqishi1"] =     "2021-06-02 00:00:00";
       $m["likaijieshu1"] =    "2031-06-02 23:59:59";
       $m["jingruqishi2"] =    "2021-06-02 00:00:00";
       $m["jingrujieshu2"] =   "2031-06-02 23:59:59";
       $m["likaiqishi2"] =     "2021-06-02 00:00:00";
       $m["likaijieshu2"] =    "2031-06-02 23:59:59";
       $m["jingruqishi3"] =    "2021-06-02 00:00:00";
       $m["jingrujieshu3"] =   "2031-06-02 23:59:59";
       $m["likaiqishi3"] =     "2021-06-02 00:00:00";
       $m["likaijieshu3"] =    "2031-06-02 23:59:59";
       $m["jingruqishi4"] =    "2021-06-02 00:00:00";
       $m["jingrujieshu4"] =   "2031-06-02 23:59:59";
       $m["likaiqishi4"] =     "2021-06-02 00:00:00";
       $m["likaijieshu4"] =    "2031-06-02 23:59:59";
       $m["staffgender"] =    "男";
       $m["staffage"] =   "9";
       $m["picfilename"] =    "pic/";
        

        // halt($m);
        $msg = json_encode($m);
        $this->dwsendtoserver($msg);

        // INSERT INTO `dwzuapairenlian`.`staffbasesetting` (`rowid`,
        //  `staffnum`,
        //  `staffname`,
        //  `signature`,
        //  `cardnum`,
        //  `departmentname`,
        //  `departmentID`,
        //  `controlerNum`,
        //  `gatenum`,
        //  `periodofvalitystart`,
        //  `periodofvalityend`,
        //  `jingruqishi1`,
        //  `jingrujieshu1`,
        //  `likaiqishi1`,
        //  `likaijieshu1`,
        //  `jingruqishi2`,
        //  `jingrujieshu2`,
        //  `likaiqishi2`,
        //  `likaijieshu2`,
        //  `jingruqishi3`,
        //  `jingrujieshu3`,
        //  `likaiqishi3`,
        //  `likaijieshu3`,
        //  `jingruqishi4`,
        //  `jingrujieshu4`,
        //  `likaiqishi4`,
        //  `likaijieshu4`,
        //  `staffgender`,
        //  `staffage`,
        //  `picfilename`) VALUES (1,
        //  '1',
        //  'admin',
        //  'e10adc3949ba59abbe56e057f20f883e',
        //  '1',
        //  'hr',
        //  '1',
        //  'ALL',
        //  'all',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  '2018-01-01 00:00:00',
        //  '2028-01-01 23:59:59',
        //  'nan',
        //  0,
        //  'wu');
    }







    public function dwsendtoserver($msg,$TCPport=1119)
	{		
		if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false)
		{
//	        echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        $string = "socket_create() 1failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
			socket_clear_error();
//			socket_close($sock);
			return false;
        }else
		{
		    // echo "socket_create OK.<br/>";
//			$string = "socket_create() 2failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
		}
		if(socket_connect($sock, '127.0.0.1', $TCPport)===false)
		{
//		socket_bind($sock, '127.0.0.1', 0);
//			file_put_contents("test.log","\n socket_connect1: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
			socket_clear_error();
			socket_close($sock);
			return false;
		}
		if(socket_sendto($sock, $msg, strlen($msg),0,"127.0.0.1",$TCPport)===false)
		{
/*			    $err =  socket_strerror() ;
			echo "err:".$err.'<br/>';
			return array("Fault"=>$err);*/
//				file_put_contents("test.log","2 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"ERROR\"}";
			socket_clear_error();
			socket_close($sock);
			return false;
		}else
		{
//			    echo 'sendto client message:'.$msg3.'message len:'.strlen($msg3).'<br/>';
//				file_put_contents("test.log","3 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"OK\"}";
		}
		socket_clear_error();
		socket_close($sock);
		return true;
	}


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        // $data =json_decode('{"dwdevice":"2021001","trans_id":"494fb911ee981b6595d8251064de432a","cmd_code":"DW_UPDATE_USERINFO","idcard":"9","userid":"9","staffsign":"","departmentname":"9","name":"9","gatenumber":"all","periodofvalitystart":"2021-06-02 00:00:00","periodofvalityend":"2031-06-02 23:59:59","jingruqishi1":"2021-06-02 00:00:00","jingrujieshu1":"2031-06-02 23:59:59","likaiqishi1":"2021-06-02 00:00:00","likaijieshu1":"2031-06-02 23:59:59","jingruqishi2":"2021-06-02 00:00:00","jingrujieshu2":"2031-06-02 23:59:59","likaiqishi2":"2021-06-02 00:00:00","likaijieshu2":"2031-06-02 23:59:59","jingruqishi3":"2021-06-02 00:00:00","jingrujieshu3":"2031-06-02 23:59:59","likaiqishi3":"2021-06-02 00:00:00","likaijieshu3":"2031-06-02 23:59:59","jingruqishi4":"2021-06-02 00:00:00","jingrujieshu4":"2031-06-02 23:59:59","likaiqishi4":"2021-06-02 00:00:00","likaijieshu4":"2031-06-02 23:59:59","staffgender":"男","staffage":"9","picfilename":"pic/"}',true);
        // // halt($data);
        // foreach ($data as $k => $v) {
        //     echo '["'.$k.'"] = '. 
        // }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;

                $indata = $params;
                $indata['id'] = $ids;
                $this->insert_student_params($indata);

                
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }




    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



     // 连接卡的数据库
     public function card_db(){
        $new =     Db::connect([
            // 数据库类型
            'type'    => 'mysql',
            // 数据库连接DSN配置
            'dsn'     => '',
            // 服务器地址
            'hostname'  => '127.0.0.1',
            // 数据库名
            'database'  => 'dwzuapairenlian',
            // 数据库用户名
            'username'  => 'card',
            // 数据库密码
            'password'  => 'card',
            // 数据库连接端口
            'hostport'  => '3306',
            // 数据库连接参数
            'params'   => [],
            // 数据库编码默认采用utf8
            'charset'   => 'utf8',
            // 数据库表前缀
            'prefix'   => '',
        ]);
        return $new;
    }
}
